package org.ala.tiktools.rpc.kcp.protocol.sender.queue;

import org.ala.tiktools.rpc.kcp.protocol.IKcpSenderQueue;
import org.ala.tiktools.rpc.kcp.protocol.segment.KcpSegment;
import org.ala.tiktools.tools.queue.DoubleLinkedQueue;
import org.ala.tiktools.tools.queue.IQueueIterator;

/**
 *
 *	@author ala
 *	@date 2025年4月27日
 */
public class KcpSenderLinkedQueue extends DoubleLinkedQueue<KcpSegment> implements IKcpSenderQueue {


	/**
	 * 	确认una
	 * 	<p>	删除una之前已经确认收到的
	 */
	@Override
	public int parseUna(long una) {
		IQueueIterator<KcpSegment> iterator = firstIterator();
		int cnt = 0;
		KcpSegment seg = null;
		while (iterator.hasNext() && (seg = iterator.current()).getSn() < una) {
			seg.recycle(true);
			iterator.removeAndNext();
			cnt++;
		}
		return cnt;
	}


	/**
	 * 	确认ack中的sn号
	 * 	<p>	小于等于sn号的seg中，找到等于sn号的，删掉
	 */
	@Override
	public void parseAck(long sn) {
		IQueueIterator<KcpSegment> iterator = firstIterator();
		KcpSegment seg = null;
		while (iterator.hasNext() && (seg = iterator.current()).getSn() <= sn) {
			if (seg.getSn() == sn) {
				iterator.removeAndNext();
				break;
			}
			iterator.next();
		}
	}

	
	/**
	 * 	处理ackSn
	 * 	<p>	所有小于ackSn的seg，其fastAck++
	 */
	@Override
	public void parseFastack(long ackSn) {
		IQueueIterator<KcpSegment> iterator = firstIterator();
		KcpSegment seg = null;
		while (iterator.hasNext() && (seg = iterator.next()).getSn() < ackSn) {
			seg.incrFastAck();
		}
	}


	@Override
	public void clear() {
		Node<KcpSegment> crt = HEAD.getNext();
		while (crt != TAIL) {
			Node<KcpSegment> nxt = crt.getNext();
			remove(crt);
			crt.getVal().recycle(true);
			crt = nxt;
		}
		HEAD.setNext(TAIL); TAIL.setPrev(HEAD);
		size = 0;
	}
	
}
